﻿using System.Windows.Controls;
using System.Windows.Media;
using System.Windows;

namespace Bravura.Editing.Common.Controls
{
	/// <summary>
	/// Represents a working area for designing a model visually.
	/// </summary>
	public class WorkGrid : Grid
	{
		#region Fields

		private static int _mw = 3;
		private static int _mh = 3;

		private GridCanvas _gridCanvas = null;
		private int _cellsWide = _mw;
		private int _cellsHigh = _mh;

		#endregion

		public WorkGrid()
		{
			_gridCanvas = new GridCanvas();
			_gridCanvas.Margin = new Thickness(10.0);
			this.Children.Add(_gridCanvas);

			Border border1 = new Border();
			border1.Margin = new Thickness(10.0);
			border1.CornerRadius = new CornerRadius(10.0);
			border1.BorderBrush = new SolidColorBrush(Colors.Black);
			border1.BorderThickness = new Thickness(1.0);
			this.Children.Add(border1);

			Border border2 = new Border();
			border2.Margin = new Thickness(0.0);
			border2.CornerRadius = new CornerRadius(15.0);
			border2.BorderBrush = new SolidColorBrush(Colors.White);
			border2.BorderThickness = new Thickness(10.0);
			this.Children.Add(border2);

			Resize();
		}

		#region Properties

		/// <summary>
		/// Get/set the number of cells wide this working grid is.
		/// </summary>
		public int CellsWide
		{
			get { return _cellsWide; }
			set { _cellsWide = value; Resize(); }
		}

		/// <summary>
		/// Get/set the number of cells high this working grid is.
		/// </summary>
		public int CellsHigh
		{
			get { return _cellsHigh; }
			set { _cellsHigh = value; Resize(); }
		}

		public double GridWidth
		{
			get { return _gridCanvas.GridWidth; }
			set { _gridCanvas.GridWidth = value; _gridCanvas.GridLeft = value / 4.0; Resize(); }
		}

		public double GridHeight
		{
			get { return _gridCanvas.GridHeight; }
			set { _gridCanvas.GridHeight = value; _gridCanvas.GridTop = value / 4.0; Resize(); }
		}

		public Color GridColor
		{
			get { return _gridCanvas.GridColor; }
			set { _gridCanvas.GridColor = value; }
		}

		public Brush GridBackground
		{
			get { return _gridCanvas.Background; }
			set { _gridCanvas.Background = value; }
		}

		#endregion

		#region Public

		public void ClearChildren()
		{
			_gridCanvas.Children.Clear();
		}

		public void PlaceChild(int x, int y, Control child)
		{
			_gridCanvas.PlaceChild(x, y, child);
		}

		#endregion

		#region Private

		private void Resize()
		{
			if (_cellsWide < _mw) _cellsWide = _mw;
			this.Width = (_cellsWide * _gridCanvas.GridWidth) + (2.0 * _gridCanvas.GridLeft) + 17.0;
			if (_cellsHigh < _mh) _cellsHigh = _mh;
			this.Height = (_cellsHigh * _gridCanvas.GridHeight) + (2.0 * _gridCanvas.GridTop) + 17.0;
		}

		#endregion
	}
}
